package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        String key= RedisConstants.CACHE_SHOPTYPE_KEY;
        //先查redis
        Long size = stringRedisTemplate.opsForList().size(key);
        if(size!=null && size>0){
            List<String> shopTypesJSON = stringRedisTemplate.opsForList().range(key, 0, size - 1);
            List<ShopType> shopTypes=new ArrayList<>();
            shopTypesJSON.forEach(shopTypeJSON->{
                shopTypes.add(JSONUtil.toBean(shopTypeJSON, ShopType.class));
            });
            return Result.ok(shopTypes);
        }
        //再查数据库
        List<ShopType> res = query().orderByAsc("id").list();
        if(res ==null || res.isEmpty()){
            return Result.fail("找不到商铺类型表！");
        }
        //写入redis
        List<String> shopTypesJSON=new ArrayList<>();
        res.forEach(shopType->{
            shopTypesJSON.add(JSONUtil.toJsonStr(shopType));
        });
        stringRedisTemplate.opsForList().rightPushAll(key, shopTypesJSON);
        return Result.ok(res);
    }
}
